package com.zbkj.crmeb.merchant.admin.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CheckAdminToken;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.PageInfo;
import com.utils.PhoneUtil;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.BrandTypeEnum;
import com.zbkj.crmeb.merchant.admin.service.MerInsertUserService;
import com.zbkj.crmeb.merchant.api.service.MerOrderService;
import com.zbkj.crmeb.store.model.ChannelUserUpload;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.service.ChannelUserUploadService;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.request.UserMemberLevelRequest;
import com.zbkj.crmeb.user.request.UserRequest;
import com.zbkj.crmeb.user.request.UserSearchRequest;
import com.zbkj.crmeb.user.request.UserUpdateIntegralRequest;
import com.zbkj.crmeb.user.response.UserLevelResponse;
import com.zbkj.crmeb.user.response.UserResponse;
import com.zbkj.crmeb.user.service.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;

/**
 * 用户表 前端控制器
 */
@RestController("merUserController")
@RequestMapping("api/admin/mer/user")
@Api(tags = "会员管理")
@Validated
public class MerUserController extends AdminBaseController {
    @Autowired
    private UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    CheckAdminToken checkAdminToken;
    @Autowired
    private MerOrderService orderService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private MerInsertUserService merInsertUserService;
    @Autowired
    private ChannelUserUploadService channelUserUploadService;

    /**
     * 分页显示用户表
     * @param request 搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-04-10
     */
    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserResponse>> getList(@ModelAttribute UserSearchRequest userSearchRequest, @ModelAttribute PageParamRequest pageParamRequest, HttpServletRequest request){
        userSearchRequest.setMerId(getMerId(request));
        CommonPage<UserResponse> userCommonPage = CommonPage.restPage(userService.getList(userSearchRequest, pageParamRequest));
        return CommonResult.success(userCommonPage);
    }

    /**
     * 分页显示用户表
     * @author Mr.Zhang
     * @since 2020-04-10
     */
    @ApiOperation(value = "团长列表")
    @RequestMapping(value = "/leader/list", method = RequestMethod.GET)
    public CommonResult<Object> getLeaderList(HttpServletRequest request){
        return CommonResult.success(userService.list(Wrappers.<User>lambdaQuery()
                .eq(User::getMerId, getMerId(request))
                .eq(User::getStatus, true)
                .eq(User::getHeadFlag, true)
                .orderByAsc(User::getUid))
        );

    }

    /**
     * 加减积分
     * @author songjichao
     * @since 2021-09-27
     */
    @ApiOperation(value = "商户后台加减积分")
    @RequestMapping(value = "/updateIntegral", method = RequestMethod.GET)
    public CommonResult<Object> updateIntegral(@Validated UserUpdateIntegralRequest request){
        if (userService.updateIntegral(request)) {
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 根据参数类型查询会员对应的信息
     * @param userId Integer 会员id
     * @param type int 类型 0=消费记录，1=积分明细，2=签到记录，3=持有优惠券，4=余额变动，5=好友关系
     * @param pageParamRequest PageParamRequest 分页
     * @author stivepeim
     * @since 2020-04-10
     */
    @ApiOperation(value="用户详情")
    @RequestMapping(value = "/infobycondition", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",example = "1", required = true),
            @ApiImplicitParam(name = "type", value="0=消费记录，1=积分明细，4=余额变动", example = "0"
                    , required = true)
    })
    public CommonResult<CommonPage<T>> infoByCondition(@RequestParam(name = "userId") @Valid Integer userId,
                                                       @RequestParam(name = "type") @Valid @Max(5) @Min(0) int type,
                                                       @ModelAttribute PageParamRequest pageParamRequest){
        return CommonResult.success(CommonPage.restPage((List<T>)userService.getInfoByCondition(userId,type,pageParamRequest)));
    }

    @ApiOperation(value = "商户后台积分配置查询")
    @RequestMapping(value = "/enableIntegral", method = RequestMethod.GET)
    public CommonResult<Object> enableIntegral(HttpServletRequest request){
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        JSONArray merIds = JSONArray.parseArray(systemAdmin.getMerId());
        if(null != systemAdmin && CollectionUtils.isEmpty(merIds)) {
            return CommonResult.success();
        }
        Integer merId = merIds.getInteger(0);
//        ChannelMerchant channelMerchant = channelMerchantService.getById(merIds.getInteger(0));
        return CommonResult.success(orderService.enableIntegral(merId));
    }

    @ApiOperation(value = "批量设置标签")
    @PutMapping(value = "/bindingTag")
    public CommonResult<Object> bindingTag(@ApiParam(value = "标签id", required = true) @RequestParam(value = "tagId") Integer tagId,
                                             @ApiParam(value = "用户id集合", required = true) @RequestParam(value = "userIdList") List<Integer> userIdList,
                                             HttpServletRequest servletRequest){
        return CommonResult.success(userService.bindingTag(tagId,userIdList,getMerId(servletRequest)));
    }

    @ApiOperation(value = "移除用户标签")
    @PutMapping(value = "/removeTag")
    public CommonResult<Object> removeTag(@ApiParam(value = "标签id", required = true) @RequestParam(value = "tagId") Integer tagId,
                                           @ApiParam(value = "用户id", required = true) @RequestParam(value = "userId") Integer userId,
                                           HttpServletRequest servletRequest){
        return CommonResult.success(userService.removeTag(tagId,userId,getMerId(servletRequest)));
    }

    @ApiOperation(value = "批量发放优惠券")
    @PutMapping(value = "/binding/coupon")
    public CommonResult<Object> binCouponUser(@ApiParam(value = "优惠券id", required = true) @RequestParam(value = "couponId") Integer couponId,
                                              @ApiParam(value = "用户id集合", required = true) @RequestParam(value = "userIdList") List<Integer> userIdList,
                                              HttpServletRequest servletRequest) {
        return CommonResult.success(userService.binCouponUser(couponId, userIdList, getMerId(servletRequest)));
    }

    @ApiOperation(value = "用户编辑")
    @RequestMapping(value = "/updateBase", method = RequestMethod.POST)
    public CommonResult<Object> updateBase(@RequestBody UserRequest userRequest, HttpServletRequest request){
        if(!PhoneUtil.validator(userRequest.getPhone())){
            return CommonResult.validateFailed("请输入正确的手机号");
        }
        User user = new User();
        BeanUtils.copyProperties(userRequest,user);
        if (user.getDistributorFlag()){
            user.setIsPromoter(true);
        }
        if(!user.getPhone().startsWith("+86")){
            user.setPhone("+86 "+user.getPhone());
        }
        return userService.updateBase(user) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value="用户编辑详情")
    @RequestMapping(value = "/getUserEditDetails", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", required = true)
    })
    public CommonResult<UserResponse> getUserEditDetails(@RequestParam Integer uid,HttpServletRequest servletRequest){
        return CommonResult.success(userService.getUserEditDetails(uid,getMerId(servletRequest)));
    }

    @ApiOperation(value = "用户等级记录列表")
    @GetMapping(value = "/list/level")
    public CommonResult<CommonPage<UserLevelResponse>> getUserLevelList(UserMemberLevelRequest request, HttpServletRequest servletRequest){
        PageInfo<UserLevelResponse> pageInfo = userService.getUserLevelList(request,getMerId(servletRequest));
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    @ApiOperation(value = "添加用户")
    @PutMapping(value = "/add")
    public CommonResult<Object> addUser(@ApiParam(value = "手机号", required = true) @RequestParam(value = "phone") String phone, HttpServletRequest servletRequest){
        if(!PhoneUtil.validator(phone)){
            return CommonResult.validateFailed("请输入正确的手机号");
        }
        return userService.addUser(phone,getMerId(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "添加用户（用户列表处）")
    @PostMapping(value = "/add/employee")
    public CommonResult<Boolean> addBankUser(@ApiParam(value = "真实姓名", required = true) @RequestParam(value = "realName") String realName,
                                            @ApiParam(value = "手机号", required = true) @RequestParam(value = "phone") String phone, HttpServletRequest request){
        if (StringUtils.isBlank(realName) || StringUtils.isBlank(phone)){
            throw new CrmebException("姓名或手机号不能为空");
        }
        return CommonResult.success(merInsertUserService.saveUser(realName, phone, getMerId(request)));
    }

    @ApiOperation(value = "批量导入用户信息列表")
    @GetMapping(value = "/list/excel/info")
    public CommonResult<CommonPage<ChannelUserUpload>> getList(PageParamRequest pageParamRequest, HttpServletRequest request){
        return CommonResult.success(CommonPage.restPage(channelUserUploadService.getList(pageParamRequest, getMerId(request))));
    }

    @ApiOperation(value = "判断优惠券指定手机号客户")
    @GetMapping(value = "/phone")
    public CommonResult<Map<String, List<String>>> getCouponUserPhoneInfo(String phones, HttpServletRequest request) {
        return CommonResult.success(userService.userExistByPhones(phones, getMerId(request)));
    }

}



